<!DOCTYPE html>
<html>

<head>
    <title>动态内容编辑器</title>
    <style>
        body {
            display: flex;
            flex-direction: column;
            align-items: center;
            font-family: Arial, sans-serif;
        }

        .container {
            display: flex;
            width: 90%;
            gap: 20px;
            margin-top: 20px;
        }

        .preview,
        .editor {
            flex: 1;
            border: 1px solid #ccc;
            padding: 20px;
            border-radius: 8px;
        }

        .title-list {
            width: 90%;
            margin: 20px 0;
            padding: 10px;
            border: 1px solid #ddd;
        }

        .title-item {
            display: inline-block;
            margin: 5px;
            padding: 8px;
            background: #f0f0f0;
            border-radius: 4px;
            cursor: pointer;
            position: relative;
        }

        .title-item:hover .delete-btn {
            display: inline-block;
        }

        .delete-btn {
            display: none;
            background: #ff4444;
            color: white;
            border: none;
            border-radius: 50%;
            width: 16px;
            height: 16px;
            margin-left: 5px;
            cursor: pointer;
        }

        #content {
            width: 100%;
            height: 200px;
            margin: 10px 0;
        }

        .placeholder-row {
            margin: 10px 0;
            padding: 10px;
            border: 1px solid #eee;
        }

        .cell-group {
            display: flex;
            gap: 5px;
            align-items: center;
            margin: 5px 0;
        }

        .invalid {
            border-color: red !important;
        }

        .preview-content {
            white-space: pre-wrap;
        }

        .placeholder {
            text-decoration: underline;
        }

        .single {
            background-color: #ffff00;
        }

        .multiple {
            background-color: #ffcccc;
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="preview">
            <h2 id="preview-title"></h2>
            <div id="preview-content" class="preview-content"></div>
        </div>
        <div class="editor">
            <input type="text" id="title" placeholder="输入标题" style="width: 100%; height: 30px;"
                oninput="updatePreview();">
            <textarea id="content" placeholder="输入内容（使用%(标记)格式添加占位符）" oninput="updatePreview();"></textarea>
            <div id="placeholder-rows"></div>
            <button onclick="saveContent()">保存</button>
        </div>
    </div>
    <div class="title-list" id="title-list"></div>
    <div>
        <input type="file" id="importFile" style="display: none" accept=".lua">
        <button onclick="document.getElementById('importFile').click()">导入</button>
        <button onclick="exportData()">导出</button>
    </div>

    <script>
        let currentData = [];
        let currentEditingIndex = -1;

        // 初始化事件监听
        document.getElementById('content').addEventListener('input', updatePlaceholderRows);
        document.getElementById('importFile').addEventListener('change', handleFileImport);

        function updatePlaceholderRows() {
            const content = document.getElementById('content').value;
            const matches = [...content.matchAll(/%\((\w+)\)/g)];
            const container = document.getElementById('placeholder-rows');

            // 保留现有行（如果存在）
            const existingRows = Array.from(container.querySelectorAll('.placeholder-row'));

            matches.forEach((match, index) => {
                let row = existingRows[index];
                if (!row) {
                    row = createPlaceholderRow(match[1], index);
                    container.appendChild(row);
                } else {
                    // 更新现有行的名称
                    row.firstElementChild.textContent = match[1];
                }
            });

            // 删除多余的行
            while (existingRows.length > matches.length) {
                container.removeChild(existingRows.pop());
            }
        }

        function createPlaceholderRow(name, index) {
            const div = document.createElement('div');
            div.className = 'placeholder-row';
            div.innerHTML = `
                <div>${name}</div>
                <div class="cell-group">
                    <input type="text" data-index="${index}" oninput="validateCell(this);">
                    <button onclick="addCell(this)">+</button>
                    <button onclick="removeCell(this)" disabled>-</button>
                </div>
            `;
            return div;
        }

        function validateCell(input) {
            const cells = input.parentElement.querySelectorAll('input');
            const firstValue = cells[0].value;
            const currentIndex = Array.from(cells).indexOf(input);

            if (currentIndex > 0) {
                const substrings = generateSubstrings(firstValue);
                input.classList.toggle('invalid', !substrings.includes(input.value));
            }
            updatePreview();
        }

        function generateSubstrings(str) {
            const substrings = [];
            for (let i = 0; i < str.length; i++) {
                for (let j = i + 1; j <= str.length; j++) {
                    substrings.push(str.slice(i, j));
                }
            }
            return substrings;
        }

        function addCell(btn) {
            const group = btn.parentElement;
            const inputs = group.querySelectorAll('input');
            const firstValue = inputs[0].value;

            const newInput = document.createElement('input');
            newInput.type = 'text';
            newInput.oninput = () => validateCell(newInput);

            group.insertBefore(newInput, btn);
            group.querySelector('button:last-child').disabled = false;
        }

        function removeCell(btn) {
            const group = btn.parentElement;
            const inputs = group.querySelectorAll('input');
            if (inputs.length > 1) {
                group.removeChild(inputs[inputs.length - 1]);
                group.querySelector('button:last-child').disabled = inputs.length === 2;
            }
        }

        function saveContent() {
            const title = document.getElementById('title').value;
            const content = document.getElementById('content').value;

            const source = [];
            document.querySelectorAll('.placeholder-row').forEach(row => {
                const cells = row.querySelectorAll('input');
                source.push({
                    name: row.firstElementChild.textContent,
                    origin: cells[0].value,
                    importance: Array.from(cells).slice(1).map(i => i.value)
                });
            });

            if (currentEditingIndex === -1) {
                currentData.push({ title, content, source });
            } else {
                currentData[currentEditingIndex] = { title, content, source };
            }

            updateTitleList();
            resetEditor();
        }

        function updateTitleList() {
            const list = document.getElementById('title-list');
            list.innerHTML = currentData.map((item, index) => `
                <div class="title-item" onclick="loadContent(${index})">
                    ${item.title}
                    <button class="delete-btn" onclick="deleteItem(${index})">×</button>
                </div>
            `).join('');
        }

        function loadContent(index) {
            currentEditingIndex = index;
            const data = currentData[index];
            document.getElementById('title').value = data.title;
            document.getElementById('content').value = data.content;
            updatePlaceholderRows();

            // 填充占位符行数据
            data.source.forEach((source, i) => {
                const group = document.querySelectorAll('.placeholder-row')[i].querySelector('.cell-group');
                source.importance.forEach((value, j) => {
                    if (j >= group.querySelectorAll('input').length - 1) addCell(group.querySelector('button'));
                    group.querySelectorAll('input')[j + 1].value = value;
                });
            });

            updatePreview();
            // 等待DOM更新完成
            setTimeout(() => {
                // 填充占位符行数据
                data.source.forEach((source, i) => {
                    const row = document.querySelectorAll('.placeholder-row')[i];
                    if (!row) return;

                    const group = row.querySelector('.cell-group');
                    const firstInput = group.querySelector('input');

                    // 设置第一个单元格的值
                    firstInput.value = source.origin;

                    // 清除已有额外单元格（保留第一个）
                    while (group.querySelectorAll('input').length > 1) {
                        group.removeChild(group.lastElementChild.previousElementSibling);
                    }

                    // 添加需要的单元格并填充值
                    source.importance.forEach((value, j) => {
                        addCell(group.querySelector('.add-cell')); // 触发添加按钮
                        const inputs = group.querySelectorAll('input');
                        inputs[j + 1].value = value; // j+1因为第一个是origin
                    });

                    // 更新按钮状态
                    group.querySelector('.remove-cell').disabled = group.querySelectorAll('input').length === 1;
                });

                updatePreview();
            }, 0);
        }

        function deleteItem(index) {
            currentData.splice(index, 1);
            updateTitleList();
        }

        function resetEditor() {
            currentEditingIndex = -1;
            document.getElementById('title').value = '';
            document.getElementById('content').value = '';
            document.getElementById('placeholder-rows').innerHTML = '';
            updatePreview();
        }

        function updatePreview() {
            document.getElementById('preview-title').textContent = document.getElementById('title').value;
            let content = document.getElementById('content').value;

            const matches = [...content.matchAll(/%\((\w+)\)/g)];
            matches.reverse().forEach((match, index) => {
                const source = currentData[currentEditingIndex]?.source?.[index];
                const origin = document.querySelectorAll(".cell-group input")[index].value
                const replacement = source ?
                    `<span class="placeholder ${source.importance.length ? 'multiple' : 'single'}">${origin
                    }</span>` : '';
                content = content.replace(match[0], replacement);
            });

            document.getElementById('preview-content').innerHTML = content;
        }

        function exportData() {
            const luaTable = `return {\n${currentData.map(item => `    {
        title = "${item.title}",
        origin = [[${item.content}]],
        source = {\n${item.source.map(s => `            {
                name = "${s.name}",
                origin = "${s.origin}",
                importance = {${s.importance.map(i => `"${i}"`).join(', ')}}
            }`).join(',\n')
                }
        }
    }`).join(',\n')
                }\n}`;

            const blob = new Blob([luaTable], { type: 'application/x-lua' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'export.lua';
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
        }

        function handleFileImport(e) {
            const file = e.target.files[0];
            if (!file) return;

            const reader = new FileReader();
            reader.onload = function (event) {
                try {
                    const data = new Function(event.target.result + '\nreturn _G')();
                    currentData = data.map(item => ({
                        title: item.title,
                        content: item.origin,
                        source: item.source.map(s => ({
                            name: s.name,
                            origin: s.origin,
                            importance: s.importance
                        }))
                    }));
                    updateTitleList();
                } catch (error) {
                    alert('文件解析失败');
                }
            };
            reader.readAsText(file);
        }

        // 初始示例数据
        currentData = [{
            title: '示例',
            content: '欢迎来到%(place)',
            source: [{
                name: 'place',
                origin: '示例地点',
                importance: []
            }]
        }];
        updateTitleList();
    </script>
</body>

</html>